package be.kuleuven.mume.rest;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

import org.json.JSONObject;

import be.kuleuven.mume.JSONHelper;
import be.kuleuven.mume.beans.AntwoordBean;
import be.kuleuven.mume.beans.AntwoordBean.AntwoordBeanFactory;
import be.kuleuven.mume.beans.PersoonBean;
import be.kuleuven.mume.beans.VraagBean;
import be.kuleuven.mume.beans.VraagBean.VraagBeanFactory;

@Path("/antwoord")
public class Antwoord {
	/**
	 * Rest interface for AntwoordBean objects
	 */
	private static final long serialVersionUID = 5522536807910452864L;
	private static final Logger log = Logger.getLogger(Vraag.class.getName());
	
	private static final String JSONSucces = "{\"result\": \"Succes!\"}";
	private static final String JSONNotImplemented = "{\"error\":\"needs to be implemented\"}";
	private static final String JSONError = "{\"error\":\"Error occured. See log for more details\"}";
	
	@GET
	@Path("/{vraagid}")
	@Produces ("application/json")
	public String getAntwoorden(@PathParam("vraagid") String vraagId, @QueryParam("rpp")@DefaultValue("10") long rpp, 
			@QueryParam("page")@DefaultValue("0") long page) {
		try{
			List<AntwoordBean> antwoorden = AntwoordBeanFactory.getAntwoordenForVraag(vraagId, page, rpp);
			return JSONHelper.convertToJSONResult(antwoorden).toString();

		} catch (Exception e){
			log.log(Level.SEVERE,"Exception",e);
		} /*catch (UserNotLoggedInException e) {
			return e.toJsonString();
		}*/

		return JSONError;
	}
	
	@POST
	@Path("/add")
	@Produces ("application/json")
	@Consumes ("application/json")
	public String addAntwoord(String antwoordJson){
		try{
			JSONObject object = new JSONObject(antwoordJson);
			VraagBean vraag = VraagBeanFactory.getVraagById(object.getString("vraagId"));
			PersoonBean persoon = null;
			String text = object.getString("text");
			AntwoordBean antwoord = new AntwoordBean(persoon, text, vraag.getId());
			
			antwoord.store();

			return "{\"result\": \"succes\",\"antwoordId\":\""+ antwoord.getId() + "\"}";
			
		} catch (Exception e) {
			log.log(Level.SEVERE, "Exception", e);
		}
		return JSONError;
	}
	
	@POST
	@Path("/update")
	@Produces ("application/json")
	@Consumes ("application/json")
	public String updateAntwoord(String vraagJson) {
		return JSONNotImplemented;
	}
	
	@GET
	@Path("/delete/{vraagid}")
	@Produces ("application/json")
	public String deleteAntwoord(@PathParam("vraagid")String vraagid) {
		return JSONNotImplemented;
	}
}
